<template>
  <Dialog :title="dialogTitle" v-model="dialogVisible">
    <el-form
      ref="formRef"
      :model="formData"
      :rules="formRules"
      label-width="120px"
      v-loading="formLoading"
    >


      <el-form-item label="日程时间范围" prop="scheduleTimeRange">
        <el-col :span="6">
          <el-date-picker
            v-model="formData.scheduleTimeRange"
            type="datetimerange"
            start-placeholder="请选择时间"
            end-placeholder="请选择时间"
            :default-time="defaultTime2"
            :disabled-date="disabledDate"
          />
        </el-col>
      </el-form-item>


      <el-form-item label="优先级" prop="priorityLevel" >
        <el-select v-model="formData.priorityLevel" placeholder="请输入优先级">
          <el-option
            v-for="dict in getStrDictOptions(DICT_TYPE.OA_PRIORITY_STATUS)"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>

      <el-form-item label="提醒设置" prop="reminderSetting">
        <el-select v-model="formData.reminderSetting" placeholder="请选择">
          <el-option
            v-for="dict in getStrDictOptions(DICT_TYPE.OA_REMINDER_STATUS)"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>


      <el-form-item label="日程内容" prop="scheduleContent">
        <el-input v-model="formData.scheduleContent"  type="textarea"  :rows = "4"  placeholder="请输入内容" />
      </el-form-item>

      <el-form-item label="日程详细描述" prop="scheduleDescription">
        <el-input v-model="formData.scheduleDescription"  type="textarea"  :rows = "4"  placeholder="请输入内容" />
      </el-form-item>

    </el-form>
    <template #footer>
      <el-button @click="submitForm" type="primary" :disabled="formLoading">确 定</el-button>
      <el-button @click="dialogVisible = false">取 消</el-button>
    </template>
  </Dialog>
</template>
<script setup lang="ts">
import { ScheduleArrangementApi, ScheduleArrangementVO } from '@/api/oa/schedulearrangement'
import { DICT_TYPE, getStrDictOptions } from '@/utils/dict'

/** 日程安排 表单 */
defineOptions({ name: 'ScheduleArrangementForm' })

const { t } = useI18n() // 国际化
const message = useMessage() // 消息弹窗

const dialogVisible = ref(false) // 弹窗的是否展示
const dialogTitle = ref('') // 弹窗的标题
const formLoading = ref(false) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
const formType = ref('') // 表单的类型：create - 新增；update - 修改
const formData = ref({
  id: undefined,
  scheduleTimeRange: undefined as [Date, Date] | undefined,
  startTime: undefined,
  endTime: undefined,
  scheduleContent: undefined,
  priorityLevel: undefined as string | undefined,
  reminderSetting: '0',
  scheduleDescription: undefined
})
const formRules = reactive({
  scheduleTimeRange: [{ required: true, message: '日程时间范围不能为空', trigger: 'blur' }],
  startTime: [{ required: true, message: '开始时间不能为空', trigger: 'blur' }],
  endTime: [{ required: true, message: '结束时间不能为空', trigger: 'blur' }],
  scheduleContent: [{ required: true, message: '日程内容不能为空', trigger: 'blur' }],
  priorityLevel: [{ required: true, message: '优先级不能为空', trigger: 'blur' }],
  reminderSetting: [{ required: true, message: '提醒设置不能为空', trigger: 'blur' }],
})
const formRef = ref() // 表单 Ref

/** 打开弹窗 - 修改版本，处理数据类型转换 */
const open = async (type: string, id?: number, defaultDate?: string) => {
  dialogVisible.value = true
  dialogTitle.value = t('action.' + type)
  formType.value = type
  resetForm()

  // 新增时，如果有默认日期，设置默认时间范围
  if (type === 'create' && defaultDate) {
    const defaultDateTime = new Date(defaultDate)
    const startTime = new Date(defaultDateTime)
    startTime.setHours(9, 0, 0, 0) // 默认开始时间 09:00
    const endTime = new Date(defaultDateTime)
    endTime.setHours(17, 0, 0, 0) // 默认结束时间 17:00
    ;(formData.value.scheduleTimeRange as any) = [startTime, endTime]
  }

  // 修改时，设置数据
  if (id) {
    formLoading.value = true
    try {
      const responseData = await ScheduleArrangementApi.getScheduleArrangement(id)
      formData.value = { ...responseData }

      // 处理数字类型转字符串类型，确保与字典匹配
      if (responseData.priorityLevel !== undefined && responseData.priorityLevel !== null) {
        formData.value.priorityLevel = String(responseData.priorityLevel)
      }

      if (responseData.reminderSetting !== undefined && responseData.reminderSetting !== null) {
        formData.value.reminderSetting = String(responseData.reminderSetting)
      }

      // 如果有时间范围字符串，转换为日期选择器需要的格式
      if (responseData.scheduleTimeRange && typeof responseData.scheduleTimeRange === 'string') {
        formData.value.scheduleTimeRange = parseScheduleTimeRange(responseData.scheduleTimeRange)
      }
    } finally {
      formLoading.value = false
    }
  }
}
defineExpose({ open }) // 提供 open 方法，用于打开弹窗

// 禁用过去的日期
const disabledDate = (time) => {
  // 获取今天的开始时间（00:00:00）
  const today = new Date()
  today.setHours(0, 0, 0, 0)

  // 如果选择的日期小于今天，则禁用
  return time.getTime() < today.getTime()
}


const emit = defineEmits(['success']) // 定义 success 事件，用于操作成功后的回调
const submitForm = async () => {
  // 校验表单
  await formRef.value.validate()
  // 提交请求
  formLoading.value = true
  try {
    const data = { ...formData.value } as unknown as ScheduleArrangementVO

    // 处理时间范围数据
    if (data.scheduleTimeRange && Array.isArray(data.scheduleTimeRange) && data.scheduleTimeRange.length === 2) {
      const startDate = new Date(data.scheduleTimeRange[0])
      const endDate = new Date(data.scheduleTimeRange[1])

      // 格式化为本地时间字符串 "2025-06-21 09:00至2025-06-21 17:45"
      const formatDateTime = (date) => {
        const year = date.getFullYear()
        const month = String(date.getMonth() + 1).padStart(2, '0')
        const day = String(date.getDate()).padStart(2, '0')
        const hours = String(date.getHours()).padStart(2, '0')
        const minutes = String(date.getMinutes()).padStart(2, '0')
        return `${year}-${month}-${day} ${hours}:${minutes}`
      }

      // 设置 scheduleTimeRange 为本地时间字符串格式
      data.scheduleTimeRange = `${formatDateTime(startDate)}至${formatDateTime(endDate)}`

      // 设置 startTime 和 endTime 为时间戳
      data.startTime = startDate.getTime()
      data.endTime = endDate.getTime()
    }

    if (formType.value === 'create') {
      await ScheduleArrangementApi.createScheduleArrangement(data)
      message.success(t('common.createSuccess'))
    } else {
      await ScheduleArrangementApi.updateScheduleArrangement(data)
      message.success(t('common.updateSuccess'))
    }
    dialogVisible.value = false
    // 发送操作成功的事件
    emit('success')
  } finally {
    formLoading.value = false
  }
}


// 如果需要在编辑时回显数据，还需要添加反向转换的逻辑
const parseScheduleTimeRange = (timeRangeStr) => {
  if (!timeRangeStr || typeof timeRangeStr !== 'string') return undefined

  const parts = timeRangeStr.split('至')
  if (parts.length !== 2) return undefined

  try {
    // 将北京时间字符串转换回UTC时间用于日期选择器显示
    const startDateStr = parts[0].trim()
    const endDateStr = parts[1].trim()

    // 解析北京时间并转换为UTC
    const startDate = new Date(startDateStr + '+08:00') // 指定北京时区
    const endDate = new Date(endDateStr + '+08:00')

    return [startDate, endDate]
  } catch (error) {
    console.error('解析时间范围失败:', error)
    return undefined
  }
}

console.log(getStrDictOptions(DICT_TYPE.OA_REMINDER_STATUS))

console.log(getStrDictOptions(DICT_TYPE.OA_PRIORITY_STATUS))

const defaultTime2: [Date, Date] = [
  new Date(2000, 1, 1, 9, 0, 0),
  new Date(2000, 2, 1, 18, 0, 0),
] // '12:00:00', '08:00:00'

/** 重置表单 */
const resetForm = () => {
  formData.value = {
    id: undefined,
    scheduleTimeRange: undefined,
    startTime: undefined,
    endTime: undefined,
    scheduleContent: undefined,
    priorityLevel: undefined,
    reminderSetting: '0',
    scheduleDescription: undefined
  }
  formRef.value?.resetFields()
}

</script>
